<template>
  <div id="login">
    <h1>Welcome to our recommend system!</h1>
    <h2>用户登录</h2>
    <p v-if="errorMessage" class="error-message">{{ errorMessage }}</p>
    <form>
      <div class="form-group">
        <label for="username">用户名:</label>
        <input type="text" id="username" v-model="username" required>
      </div>
      <div class="form-group">
        <label for="password">密码:</label>
        <input type="password" id="password" v-model="password" required>
      </div>
      <button type="submit" @click.prevent="login">登录</button>
    </form>
    <p>Don't have an account?
      <router-link to="/register">Register</router-link>
    </p>

  </div>

</template>
<script>
import axios from "axios";
import { ElMessage } from 'element-plus'
import Main from "@/views/Main.vue";
export default {
  name: "Login",
  data() {
    return {
      username: '',
      password: '',
      errorMessage: ''
    };
  },
  methods: {
    login() {

      axios.post(`http://localhost:5000/user/login`, {
        username: this.username,
        password: this.password
      }, {
        "Content-Type": "application/json;charset=UTF-8",
      }).then(res => {

        if (res.data.status === "SUCCESS") {
          // 登录成功
          // ElMessage({
          //   message: '登录成功！',
          //   type: 'success',
          // })
           alert("登录成功！")
          // this.$router.push({ name: 'Main', params: { username: this.username } })
          this.$router.push({ name: 'Main', params: { username: this.username } })
        } else if (res.data.status === "FAILED") {
          // 登录失败
          this.errorMessage = '用户名或密码错误';
        } else {
          this.errorMessage = '未知错误';
        }
      }).catch(error => {
        console.log(error)
      })
    },
  }
};

</script>

<style scoped>
#login{
    position: relative;
    margin-left: 500px;
    /*left: 500px;*/
}
#app {
  max-width: 400px;
  margin: 0 auto;
  padding: 20px;
  border: 1px solid #ccc;
  border-radius: 5px;
}

h1{
    margin-left: -100px;
    margin-right: -200px
}
h2 {
  text-align: center;
  margin-left: -10px;
}

.form-group {
  width: 200px;
  margin-bottom: 10px;
}

label {
  display: block;
}

input[type="text"],
input[type="password"] {
  width: 100%;
  padding: 5px;
  border: 1px solid #ccc;
  border-radius: 3px;
}

button {
  display: block;
  width: 100%;
  padding: 10px;
  background-color: #4CAF50;
  color: white;
  border: none;
  border-radius: 3px;
  cursor: pointer;
  margin-top: 20px;
}

.error-message {
  color: red;
  text-align: center;
  margin-top: 10px;
}

</style>